@echo off
setlocal enabledelayedexpansion

REM PPH Production Deployment Script - English Version
REM Supports server power failure restart, crash restart, error restart

echo ========================================
echo PPH Production Deployment - CMD Method
echo ========================================
echo.

REM Set deployment directories
set "DEPLOY_DIR=%~dp0.."
set "APP_DIR=%DEPLOY_DIR%\app"
set "LOG_DIR=%APP_DIR%\logs"
set "BACKUP_DIR=D:\PPH-Backups"

echo [INFO] Deployment directory: %DEPLOY_DIR%
echo [INFO] Application directory: %APP_DIR%
echo.

REM Step 1: Environment Check
echo [STEP 1] Environment Check
echo ========================================

REM Check administrator privileges
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Administrator privileges required
    echo Please run this script as Administrator
    pause
    exit /b 1
)
echo [OK] Administrator privileges confirmed

REM Check Node.js
node --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Node.js not found
    echo Please install Node.js 18.17.0 LTS from:
    echo https://nodejs.org/dist/v18.17.0/node-v18.17.0-x64.msi
    pause
    exit /b 1
)

for /f "tokens=*" %%i in ('node --version') do set NODE_VERSION=%%i
echo [OK] Node.js version: %NODE_VERSION%

REM Check npm
npm --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] npm not found
    pause
    exit /b 1
)

for /f "tokens=*" %%i in ('npm --version') do set NPM_VERSION=%%i
echo [OK] npm version: %NPM_VERSION%
echo.

REM Step 2: Stop existing services
echo [STEP 2] Stop Existing Services
echo ========================================

REM Check if PM2 is installed
pm2 --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [INFO] PM2 not installed, will install later
) else (
    echo [INFO] Stopping existing PM2 services...
    pm2 stop all >nul 2>&1
    pm2 delete all >nul 2>&1
    pm2 kill >nul 2>&1
    echo [OK] Existing services stopped
)

REM Clean port conflicts
echo [INFO] Cleaning port conflicts...
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3010') do taskkill /f /pid %%a >nul 2>&1
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3011') do taskkill /f /pid %%a >nul 2>&1
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3012') do taskkill /f /pid %%a >nul 2>&1
echo [OK] Port conflicts cleared
echo.

REM Step 3: Create directory structure
echo [STEP 3] Create Directory Structure
echo ========================================

if not exist "%APP_DIR%" mkdir "%APP_DIR%"
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"
if not exist "%BACKUP_DIR%" mkdir "%BACKUP_DIR%"

echo [OK] Directory structure created
echo.

REM Step 4: Install PM2
echo [STEP 4] Install PM2 Process Manager
echo ========================================

pm2 --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [INFO] Installing PM2...
    npm install -g pm2
    if %errorlevel% neq 0 (
        echo [ERROR] PM2 installation failed
        pause
        exit /b 1
    )
    echo [OK] PM2 installed successfully
) else (
    echo [OK] PM2 already installed
)

REM Verify PM2 installation
for /f "tokens=*" %%i in ('pm2 --version') do set PM2_VERSION=%%i
echo [OK] PM2 version: %PM2_VERSION%
echo.

REM Step 5: Install project dependencies
echo [STEP 5] Install Dependencies
echo ========================================

cd /d "%DEPLOY_DIR%"

REM Install root dependencies
if exist "package.json" (
    echo [INFO] Installing root dependencies...
    npm install --production
    if %errorlevel% neq 0 (
        echo [ERROR] Root dependencies installation failed
        pause
        exit /b 1
    )
    echo [OK] Root dependencies installed
)

REM Install backend dependencies
if exist "%APP_DIR%\backend\package.json" (
    echo [INFO] Installing backend dependencies...
    cd /d "%APP_DIR%\backend"
    npm install --production
    if %errorlevel% neq 0 (
        echo [ERROR] Backend dependencies installation failed
        pause
        exit /b 1
    )
    echo [OK] Backend dependencies installed
)

REM Install and build frontend
if exist "%APP_DIR%\frontend\package.json" (
    echo [INFO] Installing frontend dependencies...
    cd /d "%APP_DIR%\frontend"
    npm install
    if %errorlevel% neq 0 (
        echo [ERROR] Frontend dependencies installation failed
        pause
        exit /b 1
    )
    echo [OK] Frontend dependencies installed
    
    echo [INFO] Building frontend...
    npm run build
    if %errorlevel% neq 0 (
        echo [ERROR] Frontend build failed
        pause
        exit /b 1
    )
    echo [OK] Frontend built successfully
)

REM Install management dependencies
if exist "%DEPLOY_DIR%\management\package.json" (
    echo [INFO] Installing management dependencies...
    cd /d "%DEPLOY_DIR%\management"
    npm install --production
    if %errorlevel% neq 0 (
        echo [WARNING] Management dependencies installation failed
    ) else (
        echo [OK] Management dependencies installed
    )
)

cd /d "%DEPLOY_DIR%"
echo.

REM Step 6: Configure firewall
echo [STEP 6] Configure Windows Firewall
echo ========================================

echo [INFO] Configuring firewall rules...
netsh advfirewall firewall delete rule name="PPH-Frontend-3010" >nul 2>&1
netsh advfirewall firewall delete rule name="PPH-Backend-3011" >nul 2>&1
netsh advfirewall firewall delete rule name="PPH-Management-3012" >nul 2>&1

netsh advfirewall firewall add rule name="PPH-Frontend-3010" dir=in action=allow protocol=TCP localport=3010
netsh advfirewall firewall add rule name="PPH-Backend-3011" dir=in action=allow protocol=TCP localport=3011
netsh advfirewall firewall add rule name="PPH-Management-3012" dir=in action=allow protocol=TCP localport=3012

echo [OK] Firewall rules configured
echo.

REM Step 7: Start services
echo [STEP 7] Start Services
echo ========================================

echo [INFO] Starting PPH services with PM2...
cd /d "%DEPLOY_DIR%"

REM Set environment variables
set NODE_PATH=%CD%\node_modules
set PATH=%NODE_PATH%\.bin;%PATH%

REM Start services
pm2 start config\ecosystem.config.cjs --env production
if %errorlevel% neq 0 (
    echo [ERROR] Service startup failed
    echo Check logs: pm2 logs
    pause
    exit /b 1
)

REM Save PM2 configuration
pm2 save
echo [OK] Services started and configuration saved
echo.

REM Step 8: Configure auto-startup
echo [STEP 8] Configure Auto-startup
echo ========================================

echo [INFO] Configuring auto-startup...
pm2 startup windows >nul 2>&1
if %errorlevel% neq 0 (
    echo [WARNING] Auto-startup configuration may have failed
    echo You may need to configure manually
) else (
    echo [OK] Auto-startup configured
)
echo.

REM Step 9: Verify deployment
echo [STEP 9] Verify Deployment
echo ========================================

echo [INFO] Waiting for services to start...
timeout /t 10 /nobreak >nul

REM Check PM2 status
echo [INFO] Checking PM2 status...
pm2 list

REM Check port status
echo [INFO] Checking port status...
netstat -an | findstr :3010 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [OK] Frontend port 3010 is listening
) else (
    echo [WARNING] Frontend port 3010 not listening
)

netstat -an | findstr :3011 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [OK] Backend port 3011 is listening
) else (
    echo [WARNING] Backend port 3011 not listening
)

netstat -an | findstr :3012 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [OK] Management port 3012 is listening
) else (
    echo [WARNING] Management port 3012 not listening
)

REM Health check
echo [INFO] Performing health check...
curl -s http://localhost:3011/api/health >nul 2>&1
if %errorlevel% equ 0 (
    echo [OK] Backend health check passed
) else (
    echo [WARNING] Backend health check failed
)
echo.

REM Deployment completed
echo ========================================
echo DEPLOYMENT COMPLETED SUCCESSFULLY!
echo ========================================
echo.
echo Access URLs:
echo - Frontend: http://localhost:3010
echo - Backend API: http://localhost:3011/api
echo - Management: http://localhost:3012
echo.
echo Management Commands:
echo - Check status: pm2 list
echo - View logs: pm2 logs
echo - Restart all: pm2 restart all
echo - Stop all: pm2 stop all
echo.
echo Log files location: %LOG_DIR%
echo Backup directory: %BACKUP_DIR%
echo.

pause
